# app.py
from flask import Flask
from config import Config
from extensions import db, login_manager, migrate
import os

def create_app():
    app = Flask(__name__, 
                static_folder='static',
                static_url_path='/static')
    app.config.from_object(Config)
    
    # 确保上传目录存在
    os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
    
    # 初始化扩展
    db.init_app(app)
    login_manager.init_app(app)
    migrate.init_app(app, db)
    
    # 延迟导入路由
    with app.app_context():
        from views import main_bp
        from admin_views import admin
        
        app.register_blueprint(main_bp)
        app.register_blueprint(admin, url_prefix='/admin')
        
        # 创建数据库表
        db.create_all()
        
        # 创建默认管理员账号（如果不存在）
        admin_email = app.config['ADMIN_EMAIL']
        from models import User  # 延迟导入避免循环依赖
        admin_user = User.query.filter_by(email=admin_email).first()
        if not admin_user:
            admin_user = User(
                username='admin',
                email=admin_email,
                is_admin=True
            )
            admin_user.set_password(app.config['ADMIN_PASSWORD'])
            db.session.add(admin_user)
            db.session.commit()
            print(f"管理员账号已创建: {admin_email}")
    
    return app

# 用户加载器 - 关键！必须存在
@login_manager.user_loader
def load_user(user_id):
    """根据用户ID加载用户对象"""
    from models import User  # 延迟导入避免循环依赖
    return User.query.get(int(user_id))

app = create_app()

if __name__ == '__main__':
    app.run(debug=True)